package com.qinggeng.project.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.qinggeng.common.exception.CustomException;
import com.qinggeng.common.utils.CalendarAdjustUtils;
import com.qinggeng.common.utils.StringUtils;
import com.qinggeng.framework.config.mq.enums.MQTypeEnum;
import com.qinggeng.project.api.dto.UserAccountRecordDTO;
import com.qinggeng.project.system.domain.UserAccountRecord;
import com.qinggeng.project.system.domain.vo.ConsumptionDetailsVO;
import com.qinggeng.project.system.domain.vo.WithdrawalVO;
import com.qinggeng.project.system.dto.SysUserAccountRecordDTO;
import com.qinggeng.project.system.mapper.UserAccountRecordMapper;
import com.qinggeng.project.system.service.UserAccountRecordService;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class UserAccountRecordServiceImpl implements UserAccountRecordService {
    @Resource
    private UserAccountRecordMapper userAccountRecordMapper;



    @Override
    public boolean insertUserAccountRecord(UserAccountRecord userAccountRecord) {
        if (null ==userAccountRecord){
            throw new CustomException("userAccountRecord不能爲空");
        }
        Long messageId= userAccountRecord.getMessageId();
        if (null ==messageId){
            throw new CustomException("messageId不能為空");
        }

        UserAccountRecord accountRecord= getUserAccountRecordByMessageId(messageId);
        if (accountRecord !=null){
            return  true;
        }
         Long userId= userAccountRecord.getUserId();
         if (null ==userId){
             throw new CustomException("userId不能爲空");
         }
        BigDecimal beforeAccount= userAccountRecord.getBeforeAccount();
        if (null ==beforeAccount){
            throw new CustomException("beforeAccount 不能爲空");
        }

        BigDecimal afterAccount= userAccountRecord.getAfterAccount();
        if (null ==afterAccount){
            throw new CustomException("afterAccount 不能爲空");
        }
        Integer type=userAccountRecord.getType();
        if (null ==type){
            throw new CustomException("type 不能爲空");
        }
        Date date = new Date();
        log.info("插入系统时间 {} ",DateFormatUtils.format(date,"yyyy-MM-dd HH:mm:ss"));
        userAccountRecord.setCreateTime(date);
        userAccountRecord.setUpdateTime(date);
        final String format = DateFormatUtils.format(date, "yyyy");
        userAccountRecord.setCreateYear(format);
        userAccountRecord.setCreateMonth(CalendarAdjustUtils.getNextMonthToStr());
        userAccountRecord.setCreateDate(date);
        Instant instant = Instant.now();
        long timeStampMillis = instant.toEpochMilli();
        userAccountRecord.setCreateTimeStamp(timeStampMillis);
        return userAccountRecordMapper.insertSelective(userAccountRecord)>=1;
    }

    @Override
    public List<UserAccountRecord> listUserAccountOrderPayByLastMonth(Long userId) {
        return listUserAccountRecordByLastMonth(userId,MQTypeEnum.ORDER_PAY_ACCOUNT.getType());
    }

    @Override
    public List<UserAccountRecord> listUserAccountOrderPayByThisMonth(Long userId) {

        return listUserAccountRecordByMonth(userId,MQTypeEnum.ORDER_PAY_ACCOUNT.getType());
    }

    @Override
    public List<UserAccountRecord> listUserAccountOrderPayByThisYear(Long userId) {
       return listUserAccountRecordByYear(userId,MQTypeEnum.ORDER_PAY_ACCOUNT.getType());
    }

    @Override
    public List<UserAccountRecord> listUserAccountOrderRefundByLastMonth(Long userId) {
        return listUserAccountRecordByLastMonth(userId,MQTypeEnum.ORDER_REFUND_ACCOUNT.getType());
    }

    @Override
    public List<UserAccountRecord> listUserAccountOrderRefundByThisMonth(Long userId) {
       return listUserAccountRecordByMonth(userId,MQTypeEnum.ORDER_REFUND_ACCOUNT.getType());

    }
    @Override
    public List<UserAccountRecord> listUserAccountOrderRefundByThisYear(Long userId) {
        return listUserAccountRecordByYear(userId,MQTypeEnum.ORDER_REFUND_ACCOUNT.getType());
    }

    private  UserAccountRecord getUserAccountRecordByMessageId(Long messageId){
        Example example =new Example(UserAccountRecord.class);
        example.createCriteria().andEqualTo("messageId",messageId);
        UserAccountRecord userAccountRecord= userAccountRecordMapper.selectOneByExample(example);
        return  userAccountRecord;
    }

    private List<UserAccountRecord> listUserAccount(Example example){
        List<UserAccountRecord>   list =  userAccountRecordMapper.selectByExample(example);
        return  list;
    }

    private  List<UserAccountRecord> listUserAccountRecordByMonth(Long userId,Integer type){
        String monthToStr=CalendarAdjustUtils.getMonthToStr();
        Example example=new Example(UserAccountRecord.class);
        example.createCriteria()
                .andEqualTo("userId",userId)
                .andEqualTo("status",0)
                .andEqualTo("delFlag",0)
                .andEqualTo("type",MQTypeEnum.ORDER_PAY_ACCOUNT.getType())
                .andEqualTo("createMonth",monthToStr);
        List<UserAccountRecord> list=listUserAccount(example);
        return list;
    }

    private  List<UserAccountRecord> listUserAccountRecordByLastMonth(Long userId,Integer type){
        String monthToStr=CalendarAdjustUtils.getLastMonthToStr();
        Example example=new Example(UserAccountRecord.class);
        example.createCriteria()
                .andEqualTo("userId",userId)
                .andEqualTo("status",0)
                .andEqualTo("delFlag",0)
                .andEqualTo("type",MQTypeEnum.ORDER_PAY_ACCOUNT.getType())
                .andEqualTo("createMonth",monthToStr);
        List<UserAccountRecord> list=listUserAccount(example);
        return list;
    }

    private  List<UserAccountRecord> listUserAccountRecordByYear(Long userId,Integer type){
        String yearToStr=CalendarAdjustUtils.getYearToStr();
        Example example=new Example(UserAccountRecord.class);
        example.createCriteria()
                .andEqualTo("userId",userId)
                .andEqualTo("status",0)
                .andEqualTo("delFlag",0)
                .andEqualTo("type",type)
                .andEqualTo("createYear",yearToStr);
        List<UserAccountRecord> list=listUserAccount(example);
        return list;
    }

    //统计钱
    @Override
    public   String  sunMoney(List<UserAccountRecord> list){
        if (null ==list||list.isEmpty()){
            return UserAccountServiceImpl.ZERO;
        }
        BigDecimal b =BigDecimal.ZERO;
        for (UserAccountRecord userAccountRecord:list) {
            BigDecimal money=userAccountRecord.getMoney();
            if (null == money){
                money =BigDecimal.ZERO;
            }
            b =b.add(money);
        }
        return  b.toString();
    }
    //消费 减去 退款
    @Override
    public   String  sunMoney(List<UserAccountRecord> list,List<UserAccountRecord> list2){
        BigDecimal orderPay =new BigDecimal(sunMoney(list)) ;
        BigDecimal orderRound =new BigDecimal(sunMoney(list2)) ;
        return  orderPay.subtract(orderRound).toString();
    }

    @Override
    public List<ConsumptionDetailsVO> listConsumptionDetails(UserAccountRecordDTO userAccountRecordDTO) {
        PageHelper.startPage(userAccountRecordDTO.getPageNum(),userAccountRecordDTO.getPageSize());
        userAccountRecordDTO.setType(MQTypeEnum.ORDER_PAY_ACCOUNT.getType());

        return userAccountRecordMapper.listConsumptionDetailsVO(userAccountRecordDTO);
    }

    @Override
    public List<UserAccountRecord> listTransferToChangeDetails(UserAccountRecordDTO userAccountRecordDTO) {
        PageHelper.startPage(userAccountRecordDTO.getPageNum(),userAccountRecordDTO.getPageSize());
        List<Integer> types=new ArrayList<>();
        types.add(MQTypeEnum.RED_ENVRLOPES.getType());
        types.add(MQTypeEnum.PULL_NEW_ACCOUNT.getType());
        types.add(MQTypeEnum.MONTH_LOTTERY_ACCOUNT.getType());
        types.add(MQTypeEnum.SHARE_ACCOUNT.getType());
        types.add(MQTypeEnum.ADD_ACCOUNT.getType());
        return listUserAccountRecord(userAccountRecordDTO,types);
    }

    @Override
    public List<WithdrawalVO> listWithdrawalDetails(UserAccountRecordDTO userAccountRecordDTO) {
        PageHelper.startPage(userAccountRecordDTO.getPageNum(),userAccountRecordDTO.getPageSize());
        userAccountRecordDTO.setType(MQTypeEnum.WITHDRAWAL_ACCOUNT.getType());
        return userAccountRecordMapper.listWithdrawalDetailsVO(userAccountRecordDTO);

    }

    @Override
    public List<UserAccountRecord> listSysUserAccountRecord(SysUserAccountRecordDTO userAccountRecordDTO) {
        PageHelper.startPage(userAccountRecordDTO.getPageNum(),userAccountRecordDTO.getPageSize());
        userAccountRecordDTO.setType(MQTypeEnum.WITHDRAWAL_ACCOUNT.getType());
        return  userAccountRecordMapper.selectAll();
    }


    private    List<UserAccountRecord> listUserAccountRecord(UserAccountRecordDTO userAccountRecordDTO){
        Example example=new Example(UserAccountRecord.class);example.setOrderByClause("id desc");
        Example.Criteria criteria= example.createCriteria();
        criteria.andEqualTo("userId",userAccountRecordDTO.getUserId())
                .andEqualTo("status",0)
                .andEqualTo("delFlag",0)
                .andEqualTo("type",userAccountRecordDTO.getType());
        String start=userAccountRecordDTO.getStart();
        if (StringUtils.isNotEmpty(start)){
            criteria.andGreaterThanOrEqualTo("createDate",start);
        }
        String end=userAccountRecordDTO.getEnd();
        if (StringUtils.isNotEmpty(end)){
            criteria.andLessThanOrEqualTo("createDate",end);
        }
        List<UserAccountRecord> list=listUserAccount(example);
        return  list;
    }

    private  List<UserAccountRecord> listUserAccountRecord(UserAccountRecordDTO userAccountRecordDTO,List<Integer> types){

        if (null ==types || types.isEmpty()){
            throw  new CustomException("in 参数不能为空");
        }
        Example example=new Example(UserAccountRecord.class);example.setOrderByClause("id desc");
        Example.Criteria criteria= example.createCriteria();
        criteria.andEqualTo("userId",userAccountRecordDTO.getUserId())
                .andEqualTo("status",0)
                .andEqualTo("delFlag",0)
                .andIn("type",types);
        String start=userAccountRecordDTO.getStart();
        if (StringUtils.isNotEmpty(start)){
            criteria.andGreaterThanOrEqualTo("createDate",start);
        }
        String end=userAccountRecordDTO.getEnd();
        if (StringUtils.isNotEmpty(end)){
            criteria.andLessThanOrEqualTo("createDate",end);
        }
        List<UserAccountRecord> list=listUserAccount(example);
        return  list;
    }
}
